package com.kangtushizhe.handler;

import com.alibaba.fastjson2.JSON;
import com.kangtushizhe.entities.CommonResult;
import com.kangtushizhe.utils.JwtUtil;
import com.kangtushizhe.utils.WebUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class AppLogoutSuccessHandler implements LogoutSuccessHandler {
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private JwtUtil jwtUtil;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String authorization = request.getHeader("Authorization");
        String jwt = authorization.replace("bearer ", "");
        CommonResult result = jwtUtil.parseJWT(jwt);
        String a = StringUtils.substringBetween(result.getData().toString(), "userId=", ",");
        String b = StringUtils.substringBetween(result.getData().toString(), "userId=", "}");
        String userIdString = a != null ? a : b;
        Integer jwtUserId = Integer.valueOf(userIdString);
        redisTemplate.delete("loginToken-UserId:" + jwtUserId);
        CommonResult result1 = new CommonResult<>(200, "用户退出成功");
        String responseJson = JSON.toJSONString(result1);
        WebUtil.renderString(response, responseJson);


    }
}
